<template>
  <div>

    <el-page-header @back="goBack" :content="'账号与人口信息绑定'">
    </el-page-header>
    <div class="bindingInfo">


      <el-form ref="insertForm" :model="insertForm" label-width="80px" :inline="true" :rules="insertRules">

        <el-form-item label="姓名:" :label-width="formLabelWidth" class="formItemStyle" prop="name">
          <el-input v-model="insertForm.name" autocomplete="off" style="width: 262px" disabled="disabled"></el-input>
        </el-form-item>

        <el-form-item label="手机号:" :label-width="formLabelWidth" class="formItemStyle" prop="phoneNumber">
          <el-input v-model="insertForm.phoneNumber" autocomplete="off" style="width: 262px"
            disabled="disabled"></el-input>
        </el-form-item>

        <el-form-item label="性别:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="insertForm.gender" placeholder="请选择" style="width: 262px;" disabled="disabled">
            <el-option v-for="item in genderListData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="婚姻状况:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="insertForm.maritalStatus" placeholder="请选择" style="width: 262px;" disabled="disabled">
            <el-option v-for="item in maritalStatusOptionData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="家庭住址:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input v-model="insertForm.homeAddress" autocomplete="off" style="width: 262px"
            disabled="disabled"></el-input>
        </el-form-item>

        <el-form-item label="当前绑定账号:" :label-width="formLabelWidth" class="formItemStyle" prop="bindingUserAccount">
          <el-input v-model="insertForm.bindingUserAccount" autocomplete="off" style="width: 262px"
            disabled="disabled"></el-input>
        </el-form-item>
      </el-form>

      <el-divider></el-divider>


    </div>




    <!-- 分割线 下方是人口信息列表 -->
    <div>
      <div>
        <el-input class="findValue" v-model="query.userCode" placeholder="用户账号" @keyup.enter.native="queryUserList"
          clearable></el-input>
        <el-input class="findValue" v-model="query.userName" placeholder="用户姓名" @keyup.enter.native="queryUserList"
          clearable></el-input>
        <el-button type="primary" style="margin-top: 20px; margin-left: 15px" icon="el-icon-search"
          @click="queryUserList">搜索</el-button>
      </div>
      <div>
        <el-table :data="userData" style="width: 100%" class="menuTable" row-key="uid"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
          <el-table-column prop="account" label="用户账号">
          </el-table-column>
          <el-table-column prop="name" label="姓名">
          </el-table-column>

          <el-table-column prop="departmentName" label="部门">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.departmentName" placement="top-start">
                <span>{{ scope.row.departmentName == null ? '—' : scope.row.departmentName.length > 8 ?
                  "..." + scope.row.departmentName.substring(scope.row.departmentName.length - 8,
                    scope.row.departmentName.length) : scope.row.departmentName }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="roleNames" label="角色">

            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.roleNames" placement="top-start">
                <span>{{ scope.row.roleNames == null ? '—' : scope.row.roleNames.length > 8 ?
                  "..." + scope.row.roleNames.substring(scope.row.roleNames.length - 8,
                    scope.row.roleNames.length) : scope.row.roleNames }}</span>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column prop="bindingPopulationPhoneNum" label="绑定手机号">
          </el-table-column>

          <el-table-column prop="status" label="状态">

            <template slot-scope="scope">
              <span>{{ scope.row.status == '0' ? '禁用' : "正常" }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="230px" fixed="right">

            <template slot-scope="scope">
              <el-button type="success" round size="mini" @click="bindingUserAccount(scope.row)">绑定</el-button>
              <el-button type="danger" round size="mini" @click="unbindingUserAccount(scope.row)">解绑</el-button>
            </template>
          </el-table-column>
        </el-table>

      </div>


      <div class="pageFooterFather">
        <!-- <el-pagination v-if="total > pageSize" background layout="prev, pager, next" :total="total"
          @current-change="handleCurrentChange" class="pageFooter">
        </el-pagination> -->
        <myPagination :total="total" @PageChange="PageChange" @pageSizeChange="pageSizeChange"></myPagination>
      </div>
    </div>

  </div>
</template>

<style scoped>
.bindingInfo {
  margin-top: 90px;
  margin-left: 130px;
  height: 50%;
}

.menuTable {
  margin-top: 10px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.menuTable .cell {
  text-align: center;
}

.findValue {
  width: 13%;
  margin-top: 20px;
  margin-left: 15px;
}

.operation {
  margin-right: 50px;
  float: right;
  margin-top: 20px;
}

.formStyle {
  width: 1300px;
  margin: 20px auto;
}

.formItemStyle {
  margin-bottom: 28px;
  /* margin-left: 22px; */
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}

.pageFooterFather {
  top: 84%;
  position: relative;
  width: 100%;
}

.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}


.birthdayDateItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}

.findValue {
  width: 13%;
  margin-top: 20px;
  margin-left: 15px;
}
</style>



<script>
import {
  getPopulationList,
  updatePopulationInfo,
  getPopulationDetail

} from "./population";
import {
  binding,
  unbinding,
  getUserList,

} from "../user/user";

import {
  getFatherDepList,
} from "../department/department";
import { timeYMD } from "@/utils/utils.js";
export default {
  data() {
    return {
      userData: [], //用户数据
      formLabelWidth: "120px", //控制前面label的宽度
      insertForm: {
        // 新增弹框参数
        userName: "",
        account: "",
        roleIds: "",
        depId: "",
        status: "",
        bindingUserAccount: "",
      },
      insertRules: {
        phoneNumber: [
          {
            required: true,
            message: "手机号不能为空",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "设备名称不能为空",
            trigger: "blur",
          },
        ],
      },
      genderListData: [
        { id: '0', name: "女" }, { id: '1', name: "男" }
      ],
      residentialStatusOpion: [
        { id: '0', name: "空置" }, { id: '1', name: "在住" }
      ],
      maritalStatusOptionData: [
        { id: 0, name: "单身" }, { id: 1, name: "未婚" }, { id: 2, name: "已婚" }
      ],
      isPartyMemberOptionData: [
        { id: 0, name: "否" }, { id: 1, name: "是" }
      ],
      depmentManageData: [],
      query: {
        name: "",
        account: ""
      },
      userAccountId: "",
      populationInformationId: "",
      pageNum: 1,
      pageSize: 10,
      total: 0,
    }
  },

  activated() {
    this.populationInformationId = this.$route.query.id;
    this.getPopulationInfo(this.$route.query.id);

    let userData = JSON.parse(sessionStorage.getItem('logOnUser'))
    let unitType = userData.unitType;
    let unitId = userData.unitId;
    getFatherDepList(unitType, unitId).then((res) => {
      this.depmentManageData = res;
    });

    //刚进入页面加载
    this.queryUserList();

  },
  mounted: function () {
    //初始化选项数据

  },
  methods: {
    PageChange(e) {
      this.pageNum = e
      this.queryUserList()
    },
    pageSizeChange(e) {
      this.pageSize = e
      this.queryUserList()
    },

    /**
     *  修改
     */
    onSubmitUpdate() {
      this.insertForm.id = this.$route.query.id;
      updatePopulationInfo(this.insertForm).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: '个人信息修改成功',
            type: 'success'
          });
          this.goBack();
        } else {
          this.$message({
            message: res.message,
            type: "warning",
          });
        }

      })
    },

    /**
     *  上一页
     */
    goBack() {
      // this.$router.go(-1)
      this.$router.push({ path: '/population/management' });
    },

    //按条件查询菜单列表
    getPopulationList() {
      getPopulationList(
        {
          name: this.query.name,
          phoneNumber: this.query.phoneNumber,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          specialCode: '',
          residentialId: 0,
        }
      ).then((res) => {
        if (res.code == 200) {
          this.userData = res.data.list;
          // this.pageNum = res.pageNum;
          // this.pageSize = res.pageSize;
          this.total = res.data.total;
        } else {
          this.$message.error(res.message)
        }

      });
    },

    timeFormat(time) {
      return timeYMD(time);
    },
    bindingUserAccount(row) {
      this.userAccountId = row.id;

      if (row.status == 0) {

      }

      if (this.insertForm.phoneNumber != row.account) {
        this.$confirm("检测到绑定手机号与账号不一致，是否确认该操作", "提示", {
          iconClass: "el-icon-question",//自定义图标样式
          confirmButtonText: "确认",//确认按钮文字更换
          cancelButtonText: "取消",//取消按钮文字更换
          showClose: true,//是否显示右上角关闭按钮
          type: "warning",//提示类型  success/info/warning/error
        }).then(() => {
          //确认操作
          this.doBinding(row.account);

        }).then((data) => {
          //取消操作
        }).catch((err) => {
          //捕获异常
          console.log(err);
        });

      } else {
        this.doBinding(row.account);
      }

    },

    doBinding(account) {
      binding(this.userAccountId, this.populationInformationId, 'population_info').then((res) => {
        if (res.code == 200) {
          this.$message({
            message: '绑定成功',
            type: 'success'
          })
          this.$nextTick(() => {
            this.insertForm.bindingUserAccount = account;
            this.queryUserList();
          })

        } else {
          this.$message({
            message: res.message,
            type: "warning",
          });
        }

      });
    },

    unbindingUserAccount(row) {
      this.userAccountId = row.id;
      unbinding(this.userAccountId, this.populationInformationId).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: '解绑成功',
            type: 'success'
          })
          this.$nextTick(() => {
            this.insertForm.bindingUserAccount = "未绑定";
            this.userData = [];
            this.queryUserList();
          })

        } else {
          this.$message({
            message: res.message,
            type: "warning",
          });
        }

      });
    },


    getPopulationInfo(id) {
      getPopulationDetail(id).then((res) => {
        this.insertForm.phoneNumber = res.phoneNumber;
        this.insertForm.name = res.name;
        this.insertForm.gender = res.gender;
        this.insertForm.birthday = res.birthday;
        this.insertForm.nation = res.nation;
        this.insertForm.nationality = res.nationality;
        this.insertForm.idCardType = res.idCardType;
        this.insertForm.residentialStatus = res.residentialStatus;
        this.insertForm.homeAddress = res.homeAddress;
        this.insertForm.maritalStatus = res.maritalStatus;
        this.insertForm.isPartyMember = res.isPartyMember;
        this.insertForm.educationLevel = res.educationLevel;
        this.insertForm.nativePlace = res.nativePlace;
        this.insertForm.occupation = res.occupation;
        this.insertForm.company = res.company;
        this.insertForm.companyContacts = res.companyContacts;
        this.insertForm.companyAddress = res.companyAddress;
        this.insertForm.emergencyContact = res.emergencyContact;
        this.insertForm.notes = res.notes;
        this.insertForm.idNumber = res.idNumber;
        this.insertForm.identityType = res.identityType + "";
        this.insertForm.bindingUserAccount = res.bindingUserAccount;
      })
    },

    //按条件查询菜单列表
    queryUserList() {
      let userData = JSON.parse(sessionStorage.getItem('logOnUser'))
      let unitType = userData.unitType;
      let unitId = userData.unitId;
      getUserList(
        this.query.userCode,
        this.query.userName,
        '1',
        this.pageNum,
        this.pageSize,
        unitType,
        unitId
      ).then((res) => {
        this.userData = res.list;
        this.pageNum = res.pageNum;
        this.pageSize = res.pageSize;
        this.total = res.total;
      });
    },





  }
};
</script>